package com.qf.controller;

import com.qf.pojo.Cart;
import com.qf.pojo.User;
import com.qf.service.CartService;
import com.qf.service.impl.CartServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 购物车管理
 * @author 千锋健哥
 */
@WebServlet("/cart")
public class CartController extends BaseController{

    /**
     * 加入购物车
     * @param request
     * @param response
     * @return
     */
    public String create(HttpServletRequest request, HttpServletResponse response) {
        //1. 获取参数
        //商品id
        String pid = request.getParameter("pid");
        //从会话中获取用户信息对象
        User user = (User) request.getSession().getAttribute("loginUser");

        //2. 判断用户对象是否为空, 如果为空说明未登录或者登录超时, 从新登录
        if (user == null) {
            return "redirect:/login.jsp";
        }

        //3. 购买数量默认一件
        Integer num = 1;

        //4. 调用service完胜加入购物车操作
        Cart cart = new Cart();
        cart.setPid(Integer.parseInt(pid));
        cart.setUid(user.getId());
        cart.setNum(num);

        CartService cartService = new CartServiceImpl();
        cartService.addCart(cart);

        //5. 跳转到购物车列表方法
        return "redirect:/cart?method=show";
    }

    /**
     * 查询购物车列表数据, 并跳转到购物车列表页面
     */
    public String show(HttpServletRequest request, HttpServletResponse response) {
        //1. 获取当前登录用户
        User user = (User) request.getSession().getAttribute("loginUser");

        //2. 如果获取不到用户说明未登录或者登录超时, 需要用户从新登录
        if (user == null) {
            return "redirect:/login.jsp";
        }

        //3. 调用service根据用户id查询购物车列表
        CartService cartService = new CartServiceImpl();
        List<Cart> list = cartService.findCartByUid(user.getId());

        //4. 将购物车列表放入请求域中, 带到页面显示
        request.setAttribute("list", list);

        //5. 跳转到购物车列表页面
        return "forward:/cart.jsp";
    }
}
